import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:lx_widgets_library/alert/loading.dart';

import '../../../../../l10n/local.dart';
import '../../../../../routes/app_routes.dart';
import '../../../../models/user_model.dart';
import '../verify_code/verify_code_param.dart';
import 'state.dart';

class VerifyCompleteController extends GetxController with CacheMixin {
  // 状态
  final VerifyCompleteState state = VerifyCompleteState();

  @override
  void onInit() {
    super.onInit();

    state.phoneCode.value = GlobalService.to.phoneCode.value;

    debugPrint(
        "VerifyCompleteController onInit with arguments: ${Get.arguments}");
    if (Get.arguments != null && Get.arguments is VerifyCodeParam) {
      state.param = Get.arguments;
    } else {
      debugPrint(
          "❌ VerifyCompleteController: Missing or invalid VerifyCodeParam argument");
      Get.back();
    }
  }

  // 重置密码
  resetPasswordOnTap(String newPassword) {
    if (state.param.account == null ||
        state.param.account!.isEmpty ||
        state.param.securityToken == null ||
        state.param.securityToken!.isEmpty) {
      debugPrint("❌ resetPasswordOnTap: Missing account or securityToken");
      return;
    }
    Loading.showLoading(null);
    ApiHelper()
        .resetPassword(
            email: state.param.account!,
            password: newPassword,
            securityToken: state.param.securityToken!)
        .then((success) {
      Loading.dismiss();
      if (success) {
        Loading.showSuccess(local.setting_successful);
        Get.until((route) => route.settings.name == AppRoutes.ACCOUNT_SECURITY);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // 绑定新手机号/邮箱
  bindNewPhoneOrEmailOnTap(String account, String verifyCode,
      {bool isEmail = false}) {
    if (state.param.securityToken == null ||
        state.param.securityToken!.isEmpty) {
      debugPrint("❌ bindNewPhoneOrEmailOnTap: Missing securityToken");
      return;
    }
    Loading.showLoading(null);
    ApiHelper()
        .verifyVerificationCode(
            account: account,
            platform: isEmail ? CodePlatform.email : CodePlatform.phone,
            codeType: CodeType.bind,
            code: verifyCode)
        .then((verifyToken) {
      return isEmail
          ? ApiHelper().bindEmail(
              email: account,
              securityToken: state.param.securityToken!,
              verifyToken: verifyToken)
          : ApiHelper().bindPhoneNumber(
              phone: account,
              securityToken: state.param.securityToken!,
              verifyToken: verifyToken);
    }).then((success) {
      // 重新加载用户信息
      return ApiHelper().getUserInfo().then((userModel) {
        return cacheMixinUpdateUser(
          userModel.uid,
          phone: userModel.phone,
          email: userModel.email,
        );
      });
    }).then((success) {
      if (success) {
        Loading.showSuccess(local.setting_successful);
        Get.until((route) => route.settings.name == AppRoutes.ACCOUNT_SECURITY);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }
}
